<template>
  <div class="articles-admin">
    <!-- 面包屑导航 -->
    <Breadcrumb />
    
    <div class="page-header">
      <h1>文章管理</h1>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        发布文章
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="文章标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入文章标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="searchForm.categoryId"
            placeholder="请选择分类"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="已发布" :value="1" />
            <el-option label="草稿" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column label="文章信息" min-width="300">
          <template #default="{ row }">
            <div class="article-info">
              <img 
                v-if="row.coverImage" 
                :src="row.coverImage" 
                :alt="row.title"
                class="article-cover"
              />
              <div class="article-content">
                <div class="article-title">{{ row.title }}</div>
                <div class="article-summary">{{ row.summary || '暂无摘要' }}</div>
                <div class="article-meta">
                  <el-tag size="small" type="info">{{ row.categoryName }}</el-tag>
                  <span class="views">{{ row.viewCount }}次浏览</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="author" label="作者" width="100" />
        
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'warning'">
              {{ row.status === 1 ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="置顶" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.isTop"
              :active-value="1"
              :inactive-value="0"
              @change="handleTopChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column label="推荐" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.isRecommend"
              :active-value="1"
              :inactive-value="0"
              @change="handleRecommendChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="publishTime" label="发布时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.publishTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              v-if="row.status === 0" 
              type="success" 
              size="small" 
              @click="handlePublish(row)"
            >
              发布
            </el-button>
            <el-button type="warning" size="small" @click="handleView(row)">
              预览
            </el-button>
            <el-popconfirm
              title="确定要删除这篇文章吗？"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      :before-close="handleDialogClose"
      class="article-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="文章分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" placeholder="请输入作者名称" />
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="文章摘要" prop="summary">
              <el-input 
                v-model="form.summary" 
                type="textarea" 
                :rows="3"
                placeholder="请输入文章摘要（可选）"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="文章内容" prop="content">
              <div class="editor-wrapper">
                <RichTextEditor
                  v-model="form.content"
                  :rows="15"
                  placeholder="请输入文章内容，支持HTML格式和内嵌链接..."
                  :show-preview="false"
                />
              </div>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="封面图片">
              <el-input v-model="form.coverImage" placeholder="请输入封面图片URL" />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="外链地址">
              <el-input v-model="form.externalUrl" placeholder="外部链接（可选）" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="置顶">
              <el-switch
                v-model="form.isTop"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="推荐">
              <el-switch
                v-model="form.isRecommend"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">发布</el-radio>
                <el-radio :label="0">草稿</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button @click="handleSaveDraft" :loading="submitLoading">
            保存草稿
          </el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ form.status === 1 ? '发布文章' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Breadcrumb from '@/components/Breadcrumb.vue'
import RichTextEditor from '@/components/RichTextEditor.vue'
import { createArticle, updateArticle, deleteArticle, getArticleList } from '@/api/article'
import { getCategories } from '@/api/category'

// 搜索表单
const searchForm = reactive({
  title: '',
  categoryId: '',
  status: null,
  dateRange: []
})

// 分类列表
const categories = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 弹窗
const dialogVisible = ref(false)
const dialogTitle = computed(() => form.id ? '编辑文章' : '发布文章')
const submitLoading = ref(false)

// 表单
const formRef = ref()
const form = reactive({
  id: null,
  title: '',
  categoryId: '',
  author: '',
  summary: '',
  content: '',
  coverImage: '',
  externalUrl: '',
  isTop: 0,
  isRecommend: 0,
  status: 1
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  author: [
    { required: true, message: '请输入作者名称', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 获取分类列表
const loadCategories = async () => {
  try {
    const response = await getCategories()
    categories.value = response.data || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }
    
    // 模拟数据
    const mockData = {
      data: {
        list: [
          {
            id: 1,
            title: '2024年浙江省高职提前招生工作实施办法',
            summary: '根据《浙江省深化高校考试招生制度综合改革试点方案》等有关精神，特制定本实施办法。',
            content: '详细的招生工作实施办法内容...',
            categoryId: 1,
            categoryName: '招生政策',
            author: '招生办',
            coverImage: '/article-cover.jpg',
            viewCount: 1256,
            isTop: 1,
            isRecommend: 1,
            status: 1,
            publishTime: new Date('2024-03-15'),
            createTime: new Date('2024-03-15')
          },
          {
            id: 2,
            title: '浙江工业职业技术学院2024年提前招生简章',
            summary: '浙江工业职业技术学院2024年提前招生工作即将开始，欢迎广大考生报考。',
            content: '详细的招生简章内容...',
            categoryId: 2,
            categoryName: '招生简章',
            author: '招生办',
            coverImage: '',
            viewCount: 856,
            isTop: 0,
            isRecommend: 1,
            status: 1,
            publishTime: new Date('2024-03-14'),
            createTime: new Date('2024-03-14')
          },
          {
            id: 3,
            title: '提前招生报名注意事项',
            summary: '为了帮助考生顺利完成报名，特整理以下注意事项。',
            content: '报名注意事项详细内容...',
            categoryId: 3,
            categoryName: '报名指导',
            author: '管理员',
            coverImage: '',
            viewCount: 423,
            isTop: 0,
            isRecommend: 0,
            status: 0,
            publishTime: null,
            createTime: new Date('2024-03-13')
          }
        ],
        total: 156
      }
    }
    
    tableData.value = mockData.data.list
    pagination.total = mockData.data.total
  } catch (error) {
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    categoryId: '',
    status: null,
    dateRange: []
  })
  handleSearch()
}

// 添加
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  resetForm()
  Object.assign(form, row)
  dialogVisible.value = true
}

// 预览
const handleView = (row) => {
  window.open(`/articles/${row.id}`, '_blank')
}

// 发布
const handlePublish = async (row) => {
  try {
    // await updateArticle({ id: row.id, status: 1 })
    ElMessage.success('文章发布成功')
    getList()
  } catch (error) {
    ElMessage.error('发布失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    // await deleteArticle(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 置顶变更
const handleTopChange = async (row) => {
  try {
    // await updateArticle({ id: row.id, isTop: row.isTop })
    ElMessage.success('置顶设置更新成功')
  } catch (error) {
    ElMessage.error('置顶设置更新失败')
    row.isTop = row.isTop === 1 ? 0 : 1
  }
}

// 推荐变更
const handleRecommendChange = async (row) => {
  try {
    // await updateArticle({ id: row.id, isRecommend: row.isRecommend })
    ElMessage.success('推荐设置更新成功')
  } catch (error) {
    ElMessage.error('推荐设置更新失败')
    row.isRecommend = row.isRecommend === 1 ? 0 : 1
  }
}

// 保存草稿
const handleSaveDraft = async () => {
  try {
    await formRef.value.validate(['title', 'categoryId'])
    submitLoading.value = true
    
    const formData = { ...form, status: 0 }
    
    if (formData.id) {
      // await updateArticle(formData)
      ElMessage.success('草稿保存成功')
    } else {
      // await createArticle(formData)
      ElMessage.success('草稿创建成功')
    }
    
    dialogVisible.value = false
    getList()
  } catch (error) {
    if (error === false) return // 表单验证失败
    ElMessage.error('保存失败')
  } finally {
    submitLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (form.id) {
      // await updateArticle(form)
      ElMessage.success('更新成功')
    } else {
      // await createArticle(form)
      ElMessage.success('发布成功')
    }
    
    dialogVisible.value = false
    getList()
  } catch (error) {
    if (error === false) return // 表单验证失败
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    title: '',
    categoryId: '',
    author: '管理员',
    summary: '',
    content: '',
    coverImage: '',
    externalUrl: '',
    isTop: 0,
    isRecommend: 0,
    status: 1
  })
  formRef.value?.clearValidate()
}

// 分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  getList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getList()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  const d = new Date(date)
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${d.getFullYear()}-${month}-${day}`
}

// 页面加载时获取数据
onMounted(() => {
  loadCategories()
  getList()
})
</script>

<style lang="scss" scoped>
.articles-admin {
  padding: 24px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    h1 {
      font-size: 24px;
      color: #303133;
      margin: 0;
    }
  }
  
  .search-card {
    margin-bottom: 16px;
    
    :deep(.el-card__body) {
      padding: 20px;
    }
  }
  
  .table-card {
    :deep(.el-card__body) {
      padding: 20px;
    }
    
    .article-info {
      display: flex;
      gap: 12px;
      
      .article-cover {
        width: 60px;
        height: 45px;
        border-radius: 6px;
        object-fit: cover;
        flex-shrink: 0;
      }
      
      .article-content {
        flex: 1;
        min-width: 0;
        
        .article-title {
          font-weight: 500;
          color: #303133;
          margin-bottom: 6px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .article-summary {
          font-size: 12px;
          color: #909399;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .article-meta {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .views {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
    
    .pagination-wrapper {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
    }
  }
  
  .article-dialog {
    .editor-wrapper {
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      overflow: hidden;
      
      :deep(.el-textarea__inner) {
        border: none;
        box-shadow: none;
        resize: vertical;
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .articles-admin {
    padding: 16px;
    
    .page-header {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;
      
      h1 {
        font-size: 20px;
      }
    }
    
    .search-card {
      :deep(.el-form--inline) {
        .el-form-item {
          display: block;
          margin-bottom: 16px;
        }
      }
    }
    
    .table-card {
      :deep(.el-table) {
        font-size: 12px;
        
        .article-info {
          .article-cover {
            width: 40px;
            height: 30px;
          }
        }
      }
    }
  }
}
</style>